package com.springcloud.api.service.impl;

import com.springcloud.api.service.FeignProductService;
import com.springcloud.api.service.ProductService;
import com.springcloud.model.base.Res.BaseRes;
import com.springcloud.model.entity.Product;
import com.springcloud.model.util.JsonUtil;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author shengtao
 * @Description:
 * @date 2019/06/05 11:08
 */
@Service
public class ProductServiceImpl implements ProductService{

    private static final String PRODUCT_HOST = "http://product/product";


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancer;

    @Resource
    private FeignProductService feignProductService;

    @Override
    public List<Product> list() {
        ServiceInstance serviceInstance = loadBalancer.choose("product");
//        ResponseEntity<BaseRes> resResponseEntity = restTemplate.getForEntity(PRODUCT_HOST+"/list", BaseRes.class);
        BaseRes productList = feignProductService.list();
        List<LinkedHashMap<String, String>> data1 = (List<LinkedHashMap<String, String>>) productList.getData();
        if(!CollectionUtils.isEmpty(data1)){
            List<Product> products1 = JsonUtil.convertValue(data1, new TypeReference<List<Product>>() {});
            products1.stream().forEach(product -> System.out.println(product));
            return products1;
        }
       /* if(HttpStatus.OK == resResponseEntity.getStatusCode()){
            BaseRes res = resResponseEntity.getBody();
            List<LinkedHashMap<String, String>> data = (List<LinkedHashMap<String, String>>) res.getData();
            List<Product> products = JsonUtil.convertValue(data, new TypeReference<List<Product>>() {});
            products.stream().forEach(product -> System.out.println(product));
            return products;
        }*/
        return null;
    }
}
